#!/bin/bash
# $1 Full path to the installer - unused
# $2 Location of the temporary brew install we're moving into place
# $3 Target install location - unused
# $4 System root directory - unused
set -e

# verify the files exist
tmp_brew="$2"
if [[ ! -d "${tmp_brew:?}" ]]
then
  echo "no directory at ${tmp_brew}, exiting"
  exit 1
fi

# pick the correct target
if [[ $(uname -m) == "x86_64" ]]
then
  target="/usr/local"
else
  target="/opt/homebrew"
fi

loggedInUser=$(echo "show State:/Users/ConsoleUser" | scutil | awk '/Name :/ { print $3 }')
if [[ -f "${target}/bin/brew" ]]
then
  if [[ $(sudo -u"${loggedInUser}" git -C "${target}" branch --show-current) != "master" ]]
  then
    echo "working on brew modifications, exiting"
    rm -rf "${tmp_brew:?}/*"
    exit 0
  fi
  if [[ $("${tmp_brew}/bin/brew" --version | head -n1) != $("${target}/bin/brew" --version | head -n1) ]]
  then
    echo "already an outdated install at ${target}, updating"
    sudo -u"${loggedInUser}" "${target}/bin/brew" update --auto-update
  else
    echo "already an up-to-date install at ${target}, exiting"
  fi

  rm -rf "${tmp_brew:?}/*"
  exit 0
fi

group=$(id -gn "${loggedInUser}")

install -d -o "root" -g "wheel" -m "0755" "${target}"

cp -RX "${tmp_brew}/" "${target}"

# set permissions
chown -R "${loggedInUser}:${group}" "${target}/*"

# cleanup
rm -rf "${tmp_brew:?}/*"
